#include "messageclass.h"
#include <QDebug>
MessageClass::MessageClass(QObject *parent) : QObject(parent){}

void MessageClass::initNetwork(QString addr,qint64 port)
{
    socket=new QTcpSocket();
    socket->connectToHost(addr,port);
    connect(socket,&QTcpSocket::readyRead,this,&MessageClass::recvTcpContent);
    connect(CustomHandler::getInstance(),&CustomHandler::s_recvOneContact,this,&MessageClass::sendGetConactList);

}

void MessageClass::setCurrentOC(const QString &useroc)
{
    this->useroc=useroc;
}

void MessageClass::sendLogin(QString user, QString password)
{
    QByteArray resmsg=MyJson::getInstance()->logIn(user,password);
    qDebug()<<resmsg;
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::analysisTcpContent(const QByteArray& recv)
{
    MyJson::getInstance()->analysisJson(*Encipher::getInstance()->sha_aesDecrypt(recv));
    qDebug()<<*Encipher::getInstance()->sha_aesDecrypt(recv);
}


void MessageClass::sendMessage(QString senderoc,QString targetoc,QString str)
{
    QByteArray resmsg=MyJson::getInstance()->sendMessage(senderoc,targetoc,str);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::sendLogout(QString oc)
{
    QByteArray resmsg=MyJson::getInstance()->logOut(oc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::sendUserNameUpdate(QString useroc, QString newname)
{
    QByteArray resmsg=MyJson::getInstance()->updateUserName(useroc,newname);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::sendUserOCUpdate(QString newuseroc)
{
    QByteArray resmsg=MyJson::getInstance()->updateUserOC(useroc,newuseroc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::sendSignUp(QString useroc, QString username,QString password,QString avatar)
{
    QByteArray resmsg=MyJson::getInstance()->signUp(useroc,username,password,avatar);

    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::sendGetUserInfo(const QString &useroc)
{
    QByteArray resmsg=MyJson::getInstance()->getUserInfo(useroc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::sendGetConactList()
{
    QByteArray resmsg=MyJson::getInstance()->getContactList(useroc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}


void MessageClass::sendSearchFriednInfo(const QString &friendoc)
{
    this->friendoc=friendoc;
    QByteArray resmsg=MyJson::getInstance()->getFriendInfo(useroc,friendoc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}



void MessageClass::sendFriendApply(const QString &friendoc)
{
    QByteArray resmsg=MyJson::getInstance()->sendFriendApply(useroc,friendoc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}




void MessageClass::sendFriendResult(const QString &friendoc)
{
    QByteArray arr=MyJson::getInstance()->sendFriendApplyResult(useroc,friendoc);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(arr));
}

void MessageClass::sendUserAvatarFile(QString useroc,QString path)
{
    QByteArray resmsg=MyJson::getInstance()->updateUserAvatar(useroc,path);
    socket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void MessageClass::recvTcpContent()
{
    QByteArray arr=socket->readAll();
    analysisTcpContent(arr);
}


// KMP算法预处理函数，计算部分匹配表
std::vector<int> MessageClass::computeLPSArray(const QString &pattern)
{
    int M = pattern.length();
    std::vector<int> lps(M, 0);
    int len = 0;

    lps[0] = 0; // lps[0] is always 0
    int i = 1;

    while (i < M)
    {
        if (pattern[i] == pattern[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if (len != 0)
            {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}

// KMP搜索函数，返回所有匹配子串的起始索引
std::vector<int> MessageClass::KMPSearch(const QString &text, const QString &pattern)
{
    int N = text.length();
    int M = pattern.length();
    std::vector<int> lps = computeLPSArray(pattern);
    std::vector<int> indices;

    int i = 0; // index for text[]
    int j = 0; // index for pattern[]

    while (i < N)
    {
        if (pattern[j] == text[i])
        {
            j++;
            i++;
        }

        if (j == M)
        {
            indices.push_back(i - j);
            j = lps[j - 1];
        }
        // mismatch after j matches
        else if (i < N && pattern[j] != text[i])
        {
            // Do not match lps[0...lps[j-1]] characters,
            // they will match anyway
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
    return indices;
}

QStringList MessageClass::splitStringUsingKMP(const QString &mainString, const QString &delimiter)
{
    std::vector<int> matchIndices = KMPSearch(mainString, delimiter);
    QStringList resultList;

    int startIndex = 0;
    for (int index : matchIndices)
    {
        resultList.append(mainString.mid(startIndex, index - startIndex));
        startIndex = index + delimiter.length();
    }
    // 添加最后一个子串（如果有的话）
    resultList.append(mainString.mid(startIndex));

    return resultList;
}



